<template>
  <div class="login-form">
    <el-form ref="registerform" :model="form" label-width="80px" :rules="rules">
      <p>"易儿宝"母婴闲置用品交易平台</p>
      <p>欢迎注册</p>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="repassword">
        <el-input type="password" v-model="form.repassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  class="login-btn" @click="registerFn">立即注册</el-button>
        <el-link type="info" @click="gotoLoginFn">去登录</el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { regesterAPI } from '@/api'
export default {
  name: 'my-login',
  data () {
    const samePwdFN = (rule, value, callback) => {
      if (value !== this.form.password) {
        // 若验证失败，则调用回调函数时指定一个error对象
        callback(new Error('两次密码输入不一致。请重新输入'))
      } else {
        // 若验证成功，则直接调用回调函数即可
        callback()
      }
    }
    return {
      form: {
        username: '',
        password: '',
        repassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-z0-9]{1,10}$/, message: '用户名必须是1-10位的数字英文组合', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须为6-15位的非空字符', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: samePwdFN, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    registerFn () {
      this.$refs.registerform.validate(async valid => {
        if (valid) {
          const { data } = await regesterAPI(this.form)
          if (data.status !== 0) return this.$message.error(data.message)
          this.$message.success(data.message)
          this.$router.push('/login')
        } else {
          return false
        }
      })
    },
    gotoLoginFn () {
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
.login-form{
  background: url('../../assets/images/login.png') center;
  background-size: cover;
  height: 100%;
}
.el-form{
  position: absolute;
  width: 400px;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border: 1px #ffa6ff solid;
  border-radius: 20px;
  padding:10px 30px;
  opacity: 0.7;
  background-color: aliceblue;
}
.el-form p{
  color:#9F0050;
  font-size: 19px;
  text-align: center;
}
.login-btn{
  width: 100%;
}
.el-link{
  float: left;
}
</style>
